Get Text in Selenium
Get Text in Selenium is a WebElement method used to retrieve the visible text displayed inside a web element on a web page. It is commonly used when testers need to verify headings, labels, messages, button text, product names, menu items, table values, confirmation messages, and other visible content.
In Selenium WebDriver with Java, the getText() method is provided by the WebElement interface. It returns the visible text of the selected element as a String value. The method is especially useful for validation and verification in automated test cases.
JustAcademy's Selenium Automation Testing course covers Selenium WebDriver, locators, web elements, TestNG, automation frameworks, data-driven testing, Page Object Model, cross-browser testing, and real-time automation projects. You can learn more through the Selenium Training Course and register for a Selenium Course Demo.
1. What is getText() in Selenium?
The getText() method is used to retrieve the visible text from a web element. It is one of the most frequently used WebElement methods in Selenium automation testing.
For example, suppose a web page contains the following heading:
<h1>Welcome to Selenium Training</h1>
Selenium can locate this heading and retrieve its visible text using:
String text = driver.findElement(By.tagName("h1")).getText();
System.out.println(text);
The output will be:
Welcome to Selenium Training
2. Syntax of getText()
The basic syntax of the getText() method is:
String text = element.getText();
Where:
- element represents the WebElement from which text needs to be retrieved.
- getText() retrieves the visible text.
- String text stores the returned text.
3. How getText() Works
The getText() method works by retrieving the visible text associated with the selected WebElement.
The basic Selenium flow is:
Open Browser
↓
Open Web Page
↓
Locate Web Element
↓
Find Visible Text
↓
Call getText()
↓
Store Text in String
↓
Verify or Use Retrieved Text
For example:
WebElement heading = driver.findElement(By.id("pageTitle"));
String headingText = heading.getText();
System.out.println(headingText);
4. Simple Example of getText()
Consider the following HTML:
<h2 id="message">Login Successful</h2>
Selenium code:
WebElement message = driver.findElement(By.id("message"));
String text = message.getText();
System.out.println(text);
Output:
Login Successful
5. Complete Selenium Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetTextExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com");
WebElement heading = driver.findElement(By.tagName("h1"));
String text = heading.getText();
System.out.println("Heading Text: " + text);
driver.quit();
}
}
6. getText() with ID Locator
The getText() method can be used after locating an element with an ID.
WebElement element = driver.findElement(By.id("message"));
String text = element.getText();
System.out.println(text);
Example HTML:
<div id="message">Registration Successful</div>
Output:
Registration Successful
7. getText() with Name Locator
When an element has a name attribute, Selenium can locate it using the name locator.
WebElement element = driver.findElement(By.name("message"));
String text = element.getText();
System.out.println(text);
8. getText() with Class Name
The getText() method can also be used with an element located by its class name.
WebElement element = driver.findElement(By.className("success-message"));
String text = element.getText();
System.out.println(text);
Example:
<div class="success-message">Order Placed Successfully</div>
9. getText() with CSS Selector
CSS selectors can be used to locate the element before calling getText().
WebElement element = driver.findElement(By.cssSelector("#message"));
String text = element.getText();
System.out.println(text);
Another example:
String text = driver.findElement(By.cssSelector(".success-message")).getText();
10. getText() with XPath
XPath is commonly used when the element has complex or dynamic identification requirements.
WebElement element = driver.findElement(By.xpath("//div[@id='message']"));
String text = element.getText();
System.out.println(text);
Using text-based XPath:
String text = driver.findElement(By.xpath("//h2[contains(text(),'Successful')]")).getText();
11. getText() for Heading Verification
One common use of getText() is verifying whether the correct page heading is displayed.
String actualHeading = driver.findElement(By.tagName("h1")).getText();
String expectedHeading = "Dashboard";
if (actualHeading.equals(expectedHeading)) {
System.out.println("Heading is correct");
} else {
System.out.println("Heading is incorrect");
}
12. getText() for Login Validation
After submitting a login form, an application may display a success or error message. getText() can retrieve that message for verification.
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("Admin@123");
driver.findElement(By.id("login")).click();
WebElement message = driver.findElement(By.id("successMessage"));
String actualMessage = message.getText();
System.out.println("Message: " + actualMessage);
13. getText() with TestNG Assertion
In automation frameworks, getText() is frequently combined with TestNG assertions.
import org.testng.Assert;
String actualText = driver.findElement(By.id("successMessage")).getText();
String expectedText = "Login Successful";
Assert.assertEquals(actualText, expectedText);
If both values match, the test passes. If they do not match, the assertion fails.
14. getText() for Error Message Validation
getText() is useful for verifying validation and error messages displayed by an application.
WebElement error = driver.findElement(By.id("errorMessage"));
String errorText = error.getText();
System.out.println("Error Message: " + errorText);
For example, the page may contain:
<span id="errorMessage">Invalid username or password</span>
Selenium retrieves:
Invalid username or password
15. getText() for Button Text
getText() can retrieve visible text from buttons when the text is part of the button's visible content.
WebElement button = driver.findElement(By.id("submit"));
String buttonText = button.getText();
System.out.println("Button Text: " + buttonText);
Example:
<button id="submit">Submit Order</button>
Output:
Submit Order
16. getText() for Links
Links often contain visible text that can be retrieved using getText().
WebElement link = driver.findElement(By.linkText("Contact Us"));
String linkText = link.getText();
System.out.println(linkText);
Example:
<a href="/contact">Contact Us</a>
Output:
Contact Us
17. getText() for Navigation Menu
getText() can be used to verify menu labels displayed on a web application.
WebElement menu = driver.findElement(By.id("mainMenu"));
String menuText = menu.getText();
System.out.println(menuText);
If the menu contains multiple visible items, Selenium may return the combined visible text.
18. getText() for Product Name
In e-commerce automation, getText() can retrieve product names.
WebElement product = driver.findElement(By.cssSelector(".product-name"));
String productName = product.getText();
System.out.println("Product: " + productName);
Example:
<div class="product-name">Laptop Computer</div>
19. getText() for Product Price
Visible product prices can also be retrieved using getText().
WebElement price = driver.findElement(By.cssSelector(".product-price"));
String priceText = price.getText();
System.out.println("Price: " + priceText);
Example output:
$999
20. getText() for Table Data
Tables are common in business applications. getText() can retrieve text from table rows and cells.
WebElement cell = driver.findElement(By.xpath("//table[@id='users']//tr[2]/td[1]"));
String cellText = cell.getText();
System.out.println("Cell Value: " + cellText);
For example, if the cell contains:
<td>John Smith</td>
The returned value will be:
John Smith
21. getText() for Multiple Elements
When multiple elements need to be processed, Selenium can locate a collection of WebElements and call getText() for each element.
List<WebElement> products = driver.findElements(By.className("product-name"));
for (WebElement product : products) {
System.out.println(product.getText());
}
This approach is useful for product lists, menu items, search results, table rows, and other repeated elements.
22. getText() with findElements()
The findElements() method returns a list of WebElements. getText() can then be called on each individual element.
List<WebElement> elements = driver.findElements(By.cssSelector(".item"));
for (WebElement element : elements) {
String text = element.getText();
System.out.println(text);
}
23. getText() and Visible Text
One important characteristic of getText() is that it is intended to retrieve text that is visible to the user. Text that is hidden through CSS or otherwise not rendered visibly may not be returned in the same way as visible content.
Example:
<div>
<span>Visible Text</span>
<span style="display:none">Hidden Text</span>
</div>
When getText() is used on the appropriate visible element, Selenium is primarily concerned with the user-visible rendered text.
24. getText() vs getAttribute()
A common source of confusion is the difference between getText() and getAttribute().
| Feature | getText() | getAttribute() |
| Purpose | Retrieves visible text | Retrieves an attribute value |
| Return Type | String | String |
| Typical Use | Read headings, labels, messages | Read value, href, title, class, placeholder |
| Example | element.getText() | element.getAttribute("value") |
Example HTML:
<input id="username" value="admin">
For an input field, the typed or existing value is commonly retrieved using:
String value = driver.findElement(By.id("username")).getAttribute("value");
Using getText() on an input element generally does not retrieve its current input value.
25. getText() vs getAttribute("value")
This distinction is especially important when working with input fields.
WebElement username = driver.findElement(By.id("username"));
String text = username.getText();
String value = username.getAttribute("value");
System.out.println("getText(): " + text);
System.out.println("value attribute: " + value);
For input fields, use getAttribute("value") when the requirement is to retrieve the current field value.
26. getText() vs getDomProperty()
Modern Selenium automation may also require retrieving DOM properties. getText(), getAttribute(), and getDomProperty() serve different purposes.
| Method | Purpose | Typical Example |
| getText() | Retrieve visible text | Heading or message |
| getAttribute() | Retrieve an attribute | href, class, value |
| getDomProperty() | Retrieve a DOM property | Current property value |
27. Handling Leading and Trailing Spaces
Sometimes retrieved text may contain whitespace because of the structure or formatting of the page. Java's trim() method can be used when the test requirement is to remove leading and trailing whitespace.
String text = driver.findElement(By.id("message")).getText();
String cleanedText = text.trim();
System.out.println(cleanedText);
For more controlled comparisons, testers may also use methods such as equals(), equalsIgnoreCase(), or other String operations depending on the test requirement.
28. getText() with equals()
The equals() method can be used to compare the retrieved text with the expected text.
String actualText = driver.findElement(By.id("message")).getText();
if (actualText.equals("Login Successful")) {
System.out.println("Text matched");
} else {
System.out.println("Text did not match");
}
29. getText() with equalsIgnoreCase()
If the test requirement allows case-insensitive comparison, equalsIgnoreCase() can be used.
String actualText = driver.findElement(By.id("message")).getText();
if (actualText.equalsIgnoreCase("login successful")) {
System.out.println("Text matched");
}
30. getText() with contains()
contains() is useful when only part of the returned text needs to be verified.
String message = driver.findElement(By.id("message")).getText();
if (message.contains("Successful")) {
System.out.println("Success message displayed");
}
31. getText() with Explicit Wait
If text appears after an asynchronous operation, it may be necessary to wait until the element is visible before retrieving its text.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement message = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("successMessage"))
);
String text = message.getText();
System.out.println(text);
Explicit waits are useful for dynamically loaded messages, AJAX responses, notifications, and other elements that may not be immediately available.
32. getText() for Dynamic Web Elements
Dynamic applications may change text after a user action or server response. A test should locate the correct element and retrieve its text after the application has reached the expected state.
driver.findElement(By.id("submit")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement message = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("message"))
);
String result = message.getText();
System.out.println("Result: " + result);
33. getText() for Notifications
Notifications such as success messages, warning messages, and validation messages can be verified using getText().
WebElement notification = driver.findElement(By.cssSelector(".notification"));
String notificationText = notification.getText();
System.out.println("Notification: " + notificationText);
34. getText() for Login Success Scenario
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("Admin@123");
driver.findElement(By.id("loginButton")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement dashboard = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("dashboardTitle"))
);
String actualText = dashboard.getText();
Assert.assertEquals(actualText, "Dashboard");
35. getText() for E-Commerce Testing
In an e-commerce application, getText() can be used to verify product names, prices, cart messages, order confirmations, and checkout messages.
String productName = driver.findElement(By.cssSelector(".product-name")).getText();
String productPrice = driver.findElement(By.cssSelector(".product-price")).getText();
System.out.println("Product: " + productName);
System.out.println("Price: " + productPrice);
36. getText() for Cart Validation
driver.findElement(By.id("addToCart")).click();
WebElement cartMessage = driver.findElement(By.id("cartMessage"));
String message = cartMessage.getText();
Assert.assertTrue(message.contains("added to cart"));
37. getText() for Checkout Confirmation
WebElement confirmation = driver.findElement(By.id("orderConfirmation"));
String confirmationText = confirmation.getText();
Assert.assertTrue(confirmationText.contains("Order"));
System.out.println("Confirmation: " + confirmationText);
38. getText() in Page Object Model
In the Page Object Model design pattern, getText() operations can be placed inside page classes so that test classes remain clean and readable.
public class LoginPage {
private WebDriver driver;
private By successMessage = By.id("successMessage");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public String getSuccessMessage() {
return driver.findElement(successMessage).getText();
}
}
Test class:
String message = loginPage.getSuccessMessage();
Assert.assertEquals(message, "Login Successful");
39. getText() in TestNG Automation
@Test
public void verifyMessage() {
String actualMessage = driver.findElement(By.id("message")).getText();
Assert.assertEquals(actualMessage, "Welcome User");
}
This approach allows retrieved UI text to become part of automated validation.
40. getText() for Multiple Menu Items
List<WebElement> menuItems = driver.findElements(By.cssSelector(".menu-item"));
for (WebElement item : menuItems) {
System.out.println("Menu Item: " + item.getText());
}
This can be useful for checking navigation menus or verifying that expected options are present.
41. getText() for Search Results
List<WebElement> results = driver.findElements(By.cssSelector(".search-result"));
for (WebElement result : results) {
String resultText = result.getText();
System.out.println(resultText);
}
42. getText() for Web Tables
For dynamic tables, testers can retrieve text from individual cells or rows.
List<WebElement> rows = driver.findElements(By.cssSelector("table tbody tr"));
for (WebElement row : rows) {
System.out.println(row.getText());
}
A row-level getText() call may return the visible text from the cells contained within that row.
43. getText() for Dropdown Options
When working with a standard HTML select element, Selenium's Select class can be used to access options. getText() can then be used on individual option elements.
Select country = new Select(driver.findElement(By.id("country")));
for (WebElement option : country.getOptions()) {
System.out.println(option.getText());
}
44. getText() and Hidden Elements
getText() is intended for retrieving visible text. If content is hidden, the returned result may not contain that hidden content in the way a tester expects.
Therefore, testers should first determine whether the required text is actually visible on the page and whether the correct WebElement has been selected.
45. Common Mistake: Using getText() for Input Values
A common Selenium mistake is trying to retrieve the value typed into an input field using getText().
Incorrect approach:
String username = driver.findElement(By.id("username")).getText();
For an input field, use the value attribute:
String username = driver.findElement(By.id("username")).getAttribute("value");
46. Common Mistake: Calling getText() Before Element Is Available
If an element is loaded dynamically and the script immediately calls getText(), the test may fail because the element is not yet available or visible.
Better approach:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement message = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("message"))
);
String text = message.getText();
47. Common Mistake: Incorrect Locator
If the locator identifies the wrong element, getText() may return an unexpected value or an empty String.
Always inspect the DOM and verify that the locator points to the intended WebElement.
48. Common Mistake: Exact Text Comparison
Exact comparison can fail when the application adds extra whitespace, punctuation, dynamic values, or different capitalization.
For example:
String actual = element.getText();
Assert.assertTrue(actual.contains("Successful"));
Use partial comparison only when it matches the actual test requirement. Otherwise, an exact assertion is preferable.
49. Common Mistake: Ignoring Dynamic Content
Applications built with JavaScript frameworks may update text asynchronously. The test should synchronize with the application before retrieving the text.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("dynamicMessage"))
);
String text = element.getText();
50. Best Practices for getText()
- Use meaningful locators to identify the correct element.
- Use getText() when the requirement is to retrieve visible UI text.
- Use getAttribute("value") for input field values.
- Use explicit waits for dynamically loaded content.
- Store retrieved text in meaningful String variables.
- Use TestNG assertions for automated validation.
- Avoid unnecessary Thread.sleep() calls.
- Use contains() when partial text validation is intentionally required.
- Use equals() when the complete expected text must match.
- Keep text retrieval logic organized inside Page Object classes when using POM.
51. Advantages of getText()
| Advantage | Description |
| Simple | Easy to use and understand. |
| Useful for Validation | Helps verify visible messages and labels. |
| Supports Automation | Can be combined with assertions. |
| Works with WebElements | Can retrieve text from headings, labels, links, tables, and other elements. |
| Useful in Frameworks | Can be integrated with Page Object Model and TestNG. |
| Useful for Debugging | Helps print and inspect text displayed by the application. |
52. Limitations of getText()
- It is intended for visible text retrieval.
- It is not the appropriate method for retrieving input field values.
- Dynamic content may require synchronization.
- Incorrect locators can produce incorrect results.
- Text formatting and whitespace can affect exact comparisons.
53. Real-Time Example: Login Test
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
public class LoginTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com/login");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("Admin@123");
driver.findElement(By.id("loginButton")).click();
String actualMessage = driver.findElement(By.id("successMessage")).getText();
Assert.assertEquals(actualMessage, "Login Successful");
driver.quit();
}
}
54. Real-Time Example: Product Verification
WebElement product = driver.findElement(By.cssSelector(".product-name"));
String productName = product.getText();
if (productName.equals("Laptop Computer")) {
System.out.println("Correct product displayed");
} else {
System.out.println("Incorrect product displayed");
}
55. Real-Time Example: Error Message Verification
driver.findElement(By.id("loginButton")).click();
WebElement errorMessage = driver.findElement(By.id("loginError"));
String actualError = errorMessage.getText();
Assert.assertEquals(actualError, "Invalid username or password");
56. Real-Time Example: Table Data Verification
List<WebElement> rows = driver.findElements(By.cssSelector("#userTable tbody tr"));
for (WebElement row : rows) {
String rowText = row.getText();
System.out.println(rowText);
if (rowText.contains("John")) {
System.out.println("User found");
}
}
57. Practical Project Using getText()
A practical Selenium project can use getText() to validate a complete web application workflow.
Login
↓
Enter Username and Password
↓
Click Login
↓
Retrieve Dashboard Text
↓
Validate Dashboard
↓
Search Product
↓
Retrieve Product Name and Price
↓
Add Product to Cart
↓
Retrieve Cart Message
↓
Proceed to Checkout
↓
Retrieve Confirmation Message
↓
Validate Order Confirmation
Example validation points:
- Verify login success message.
- Verify dashboard heading.
- Verify product name.
- Verify product price.
- Verify cart confirmation.
- Verify checkout confirmation.
58. getText() Interview Questions
Q1. What is getText() in Selenium?
getText() is a WebElement method used to retrieve visible text from a web element.
Q2. What does getText() return?
It returns the retrieved text as a String.
Q3. Can getText() retrieve the value entered in an input field?
Generally, no. For an input field's current value, getAttribute("value") is commonly used.
Q4. What is the difference between getText() and getAttribute()?
getText() is used for visible text, while getAttribute() is used to retrieve an HTML attribute value.
Q5. Can getText() be used with XPath?
Yes. XPath can locate the WebElement, and getText() can then retrieve its visible text.
Q6. Can getText() be used with CSS selectors?
Yes. A CSS selector can locate the WebElement before calling getText().
Q7. How can you validate text in Selenium?
The retrieved text can be stored in a String and compared with expected text using Java String methods or TestNG assertions.
Q8. How do you handle dynamically displayed text?
Use an appropriate explicit wait to synchronize with the element before calling getText().
Q9. Can getText() retrieve hidden text?
getText() is intended for visible rendered text, so hidden content should not be treated as ordinary visible text.
Q10. Why might getText() return an empty String?
Possible reasons include selecting the wrong element, the element having no visible text, or the required content not being visible at the time of retrieval.
59. getText() Quick Reference
| Requirement | Recommended Approach |
| Retrieve visible heading | getText() |
| Retrieve visible label | getText() |
| Retrieve success message | getText() |
| Retrieve error message | getText() |
| Retrieve product name | getText() |
| Retrieve visible table text | getText() |
| Retrieve input value | getAttribute("value") |
| Retrieve href | getAttribute("href") |
| Retrieve CSS class | getAttribute("class") |
| Retrieve placeholder | getAttribute("placeholder") |
60. getText() Best Practices Checklist
- Locate the correct WebElement before calling getText().
- Use getText() for visible UI text.
- Use getAttribute("value") for input values.
- Use explicit waits for asynchronous content.
- Use meaningful variable names such as actualMessage or productName.
- Use assertions for automated validation.
- Use contains() for intentional partial-text verification.
- Use equals() for exact text verification.
- Avoid Thread.sleep() when a suitable explicit wait can be used.
- Keep reusable text retrieval methods inside Page Object classes.
61. Conclusion
The getText() method is an essential Selenium WebDriver method for retrieving visible text from web elements. It is widely used for verifying headings, labels, links, buttons, notifications, validation messages, product information, table data, and confirmation messages.
Understanding the difference between getText(), getAttribute(), and DOM property methods is important for writing reliable Selenium automation scripts. When combined with locators, explicit waits, TestNG assertions, and Page Object Model, getText() becomes an important part of real-world UI automation testing.
To learn Selenium WebDriver, Java automation, TestNG, locators, automation frameworks, and practical testing projects, visit the JustAcademy Selenium Training Course. For a course demonstration, use the JustAcademy Course Demo Registration.